#include "ringQueue.hpp"
#include <ctime>

void* consumer(void* args)
{
    RingQueue<Task>* rq = (RingQueue<Task>*)args;
    while (true)
    {
        Task t;
        // 1.从环形队列中获取任务
        rq->pop(&t);
        // 2.进行处理
        cout << pthread_self() << ", " << "消费：" << t._x << " + " << t._y << " = " << t() << endl;
        //sleep(1);
    }
}

int Add(int x, int y)
{
    return x + y;
}

void* productor(void* args)
{
    RingQueue<Task>* rq = (RingQueue<Task>*)args;
    while (true)
    {
        // 1.构建数据或任务对象，数据可能从任何地方来，那一定会有时间消耗
        int x = rand() % 10 + 1;
        usleep(rand()%1000);
        int y = rand() % 10 + 1;
        Task t(x, y, Add);
        // 2.推送到环形队列
        rq->push(t);
        cout << pthread_self() << ", " << "生产：" << x << " + " << y << " = ?" << endl;
        //sleep(1);
    }
}

int main()
{
    srand((unsigned)time(nullptr) ^ getpid());

    RingQueue<Task>* rq = new RingQueue<Task>();

    pthread_t c[2], p[2];
    pthread_create(c, nullptr, consumer, (void*)rq);
    pthread_create(c+1, nullptr, consumer, (void*)rq);
    pthread_create(p, nullptr, productor, (void*)rq);
    pthread_create(p+1, nullptr, productor, (void*)rq);

    pthread_join(c[0], nullptr);
    pthread_join(c[1], nullptr);
    pthread_join(p[0], nullptr);
    pthread_join(p[1], nullptr);

    return 0;
}